package com.faner4cloud.yun.common.util.delayqueue;

import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

/**
 * 延迟队列元素基类
 * 实现基本方法，特殊业务需要子类实现
 *
 * @summary 延迟队列元素基类
 **/
public class DelayItem<T> implements Delayed{
	/**
	 * 过期时间戳，毫秒
	 */
	private long expire;

	/**
	 * 具体数据
	 */
	private T data;

	public DelayItem(T data, long expire){
		this.data = data;
		this.expire = expire;
	}

	public long getExpire() {
		return expire;
	}

	public void setExpire(long expire) {
		this.expire = expire;
	}

	public T getData() {
		return data;
	}

	public void setData(T data) {
		this.data = data;
	}

	@Override
	public String toString(){
		return "DelayItem{" + "data=" + data.toString()
			+ ",expire=" + expire + "}";
	}

	/**
	 * 用于在优先队列中排序，超时时间近的排在最前
	 *
	 * @param o
	 * @return
	 */
	@Override
	public int compareTo(Delayed o) {
		if (o == this){
			return 0;
		}
		if (o instanceof DelayItem){
			DelayItem item = (DelayItem) o;
			long diff = this.getExpire() - item.getExpire();
			if (diff < 0){
				return -1;
			}else if (diff > 0){
				return 1;
			}else {
				return 0;
			}
		}
		long d = getDelay(TimeUnit.MILLISECONDS) - o.getDelay(TimeUnit.MILLISECONDS);
		return (d == 0) ? 0 : ((d < 0) ? -1 : 1);
	}

	/**
	 * 用于从队列中移除
	 * @param o
	 * @return
	 */
	@Override
	public boolean equals(Object o) {
		if (this == o){
			return true;
		}
		if (o == null){
			return false;
		}
		if (o instanceof DelayItem){
			DelayItem item = (DelayItem) o;
			return this.getData().equals(item.getData());
		}else {
			return false;
		}
	}

	/**
	 * 用于判断任务是否超时
	 * 超时时间和当前时间对比
	 *
	 * @param unit
	 * @return
	 */
	@Override
	public long getDelay(TimeUnit unit) {
		return unit.convert(this.getExpire() - System.currentTimeMillis(), TimeUnit.MILLISECONDS);
	}




}
